package com.jt.service;

import com.jt.dao.MenuMapper;
import com.jt.pojo.Menu;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.time.Duration;

@Service
public class MenuServiceImpl implements MenuService{

    private static final Logger log= LoggerFactory.getLogger(MenuServiceImpl.class);

    private MenuMapper menuMapper;

    private static final String KEY_PREFIX="menu";

    private ValueOperations valueOperations;

    public MenuServiceImpl(MenuMapper menuMapper, RedisTemplate redisTemplate) {
        this.menuMapper = menuMapper;
        this.valueOperations = redisTemplate.opsForValue();
    }

    @Override
    public Menu selectById(Long id) {
        //ValueOperations valueOperations = redisTemplate.opsForValue();
        Object obj = valueOperations.get(KEY_PREFIX + id);
        if (obj!=null) {
            log.info("Data from cache");
            return (Menu) obj;
        }
        log.info("Data from MySQL");
        Menu menu = menuMapper.selectById(id);
        valueOperations.set(KEY_PREFIX+id, menu, Duration.ofSeconds(60*60));
        return menu;
    }

    @Override
    public Menu insertMenu(Menu menu) {
        log.info("insert.before.menu={}",menu);
        menuMapper.insert(menu);
        log.info("insert.after.menu={}",menu);
        //ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set(KEY_PREFIX+menu.getId(), menu, Duration.ofSeconds(60*60));
        return menu;
    }

    @Override
    public Menu updateMenu(Menu menu) {
        menuMapper.updateById(menu);
        //ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set(KEY_PREFIX+menu.getId(), menu, Duration.ofSeconds(60*60));
        return menu;
    }
}
